package com.tian.print.login.model;

import com.tian.print.bean.UserInfo;
import com.tian.print.http.error.ApiException;
import com.tian.print.http.request.ApiRequest;
import com.tian.print.http.response.Response;
import com.tian.print.http.RxSchedulers;
import com.tian.print.http.response.ResponseTransformer;
import com.tian.print.app.BaseModel;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Description:
 * <br>Author：tian
 * <br>Time: 2019/5/23 20:19
 */
public class LoginModel extends BaseModel {

    private OnLoginFinishedListener onLoginFinishedListener;

    public LoginModel(OnLoginFinishedListener onLoginFinishedListener) {
        this.onLoginFinishedListener = onLoginFinishedListener;
    }

    public void login(String name, String password) {
        Disposable disposable = ApiRequest.apiClent.login(name, password, "ERP_T", "S")
                .compose(RxSchedulers.<Response<UserInfo>>compose())
                .compose(ResponseTransformer.handleResult())
                .subscribe(new Consumer<UserInfo>() {
                    @Override
                    public void accept(UserInfo userInfo) throws Exception {
                        onLoginFinishedListener.loginSuccess(userInfo);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoginFinishedListener.loginError((ApiException) throwable);
                    }
                });

        addDisposable(disposable);
    }

    /**
     * Model层的回调
     */
    public interface OnLoginFinishedListener {
        void loginSuccess(UserInfo userInfo);
        void loginError(ApiException e);
    }
}
